const { exec } = require("child_process");
const fs = require("fs");
const path = require("path");
const os = require("os");
const readSetting = require("../../lib/read_setting");
const CMD = require("../../lib/clip_video");


module.exports = (req, res) => {

    let { findPath, oldname, newname, outputPath, currentIndex, start_time, duration } = req.body;

    start_time = start_time * 1;
    duration = duration * 1;

    if (!/^\d+$/.test(start_time) || start_time < 0) return res.send({ code: 400, msg: "开始时间设置不合法", result:'',...req.body });

    if (!/^\d+$/.test(duration) || duration < 0) return res.send({ code: 400, msg: "裁剪长度设置不合法",result:'', ...req.body });

    outputPath = outputPath || readSetting().output_path || path.join(os.homedir(), 'Desktop');

    if (!findPath.trim()) return res.send({ code: 400, msg: "检索路径不存在",result:'', ...req.body });

    if (!oldname.trim() || !/\.(mp4|wmv|avi|flv|ts|webm)$/.test(oldname)) return res.send({ code: 400, msg: "源文件格式不合法",result:'', ...req.body });

    // 如果没有传递新名字，则默认跟源文件名一样
    if (!newname.trim()) newname = oldname;
    // 为防止出现多后缀的情况，先删除新名称后缀
    newname = newname.replace(/\.(mp4|avi|wmv|flv|ts|webm)$/, '');
    // 为防止用户填写的后缀不是系统支持格式
    if (!/\.(mp4|avi|wmv|flv|ts|webm)$/.test(newname)) newname = `${newname}.${oldname.split(".").pop()}`;

    // 要转换倍速的文件
    let filepath = path.resolve(findPath, oldname);

    if (!fs.existsSync(filepath)) {
        return res.send({ code: 400, msg: `路径 ${filepath} 不存在！`, result: '', ...req.body });
    }

    if (!fs.existsSync(outputPath)) {
        try {
            fs.mkdirSync(outputPath, { recursive: true });
        } catch (error) {
            return res.send({ code: 400, msg: "输出路径错误！", result: '', ...req.body });
        }
    }

    new Promise((resolve, reject) => {

        let savePath = path.resolve(outputPath, newname);

        if (fs.existsSync(savePath)) {
            return reject("目标目录下存在同名文件！！！")
        };

        let cmd = CMD(filepath, savePath, start_time, duration);

        exec(cmd, (err, stdout, stderr) => {
            if (err) return reject(err);
            resolve({ savePath, newname });
        })

    }).then(({ savePath, newname }) => {
        exec(`explorer "${outputPath}"`, (err, stdout, stderr) => {
            if (err) console.log(err);
        })
        res.send({
            code: 200,
            state: true,
            currentIndex,
            filename: newname,
            result: savePath,
            msg: `${newname} 裁剪成功！`
        })
    }).catch(err => {
        console.log(err);
        let errObj = {
            code: 500,
            state: false,
            currentIndex,
            filename: newname,
            result: err,
            msg: `${newname} 裁剪失败！`
        };
        res.send(errObj);
    })
}